/**
 *
 */
package com.zhuoyue.zhtj.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import com.eit.eitsite.common.utils.HttpUtils;
import com.google.common.collect.Maps;
import com.zhuoyue.elmt.utils.GsonUtils;
import com.zhuoyue.zhtj.common.Consts;
import com.zhuoyue.zhtj.entity.PublicInfo;
import com.zhuoyue.zhtj.sdk.https.EasyX509TrustManager;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eit.eitsite.common.persistence.Page;
import com.eit.eitsite.common.service.CrudService;
import com.zhuoyue.zhtj.entity.Wxxx;
import com.zhuoyue.zhtj.dao.WxxxDao;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信信息Service
 *
 * @author hss
 * @version 2017-08-16
 */
@Service
@Transactional(readOnly = true)
public class WxxxService extends CrudService<WxxxDao, Wxxx> {
    @Autowired
    private WxxxDao wxxxDao;

    public Wxxx get(String id) {
        return super.get(id);
    }

    public List<Wxxx> findList(Wxxx wxxx) {
        return super.findList(wxxx);
    }

    public Page<Wxxx> findPage(Page<Wxxx> page, Wxxx wxxx) {
        return super.findPage(page, wxxx);
    }

    @Transactional(readOnly = false)
    public void save(Wxxx wxxx) {
        super.save(wxxx);
    }

    @Transactional(readOnly = false)
    public void delete(Wxxx wxxx) {
        super.delete(wxxx);
    }

    public boolean checkOpeId(String openId) {
        String nickname = null;
        if (openId != null && !"".equals(openId)) {
            nickname = wxxxDao.checkOpenId(openId);
        }
        if (nickname != null) {
            return true;
        }
        return false;
    }

    /**
     * 获取微信Access_Token
     *
     * @param publicInfo
     * @param response
     * @return
     */
    public String getAccessToken(PublicInfo publicInfo, HttpServletResponse response) {
        if (publicInfo == null || publicInfo.getUrl() == null) {
            return null;
        }
        JSONObject object = HttpUtils.httpGet(Consts.url);
        if (object != null && object.get(Consts.access_token) != null) {
            return object.get(Consts.access_token).toString();
        }
        return null;
    }

    /**
     * URL编码（utf-8）
     *
     * @param source
     * @return
     */
    public static String urlEncodeUTF8(String source) {
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取微信用户信息
     *
     * @param code
     * @return
     */
    public Wxxx getWxUserInfo(String code) {
        if (code != null) {
            JSONObject jsonObject = HttpUtils.httpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Consts.appid + "&secret=" + Consts.secret + "&code=" + code + "&grant_type=authorization_code");
            String openid = "";
            String access_token = "";
            if (jsonObject.get(Consts.openid) != null) {
                openid += jsonObject.get(Consts.openid).toString();
                access_token += jsonObject.get(Consts.access_token);
                if (!"".equals(openid)) {
                    JSONObject object = HttpUtils.httpGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN");
                    try {
                        if (object.get("openid") != null) {
                            String string = new String(object.toString().getBytes(Consts.ISO_8859_1), Consts.UTF8);
                            return GsonUtils.newInstance().fromJson(string, Wxxx.class);
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    /**
     * 获取授权地址
     *
     * @return
     */
    public String getUrl() {
        String url = "http://" + Consts.domainname + "/szptApp/a/zhtj/wxxx/grantAuth";
        String redirectUrl = urlEncodeUTF8(url);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Consts.appid + "&redirect_uri=" + redirectUrl + "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
    }

    /**
     * 获取授权地址
     *
     * @return
     */
    public String getZbUrl() {
        //String url = "http://" + Consts.domainname + "/szptApp/html/broaadcast.html";
        String url = "http://www.joyue-tech.com/szptApp/html/broaadcast.html";
        String redirectUrl = urlEncodeUTF8(url);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Consts.appid + "&redirect_uri=" + redirectUrl + "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
//        return "http://"+Consts.domainname+"/szptApp/get-weixin-code.html?appid="+Consts.appid+"&scope=snsapi_base&state=hi&redirect_uri="+redirectUrl;
    }


    public String prompt() {
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + getAccess_token();
        Map<String, Object> params = Maps.newHashMap();
        Map<String, Object> scene = Maps.newHashMap();
        Map<String, Object> sceneInfo = Maps.newHashMap();
        params.put("expire_seconds", 604800);
        params.put("action_name", "QR_STR_SCENE");
        sceneInfo.put("scene_id", 1234);
        scene.put("scene", sceneInfo);
        params.put("action_info", scene);
        JSONObject jsonObject = HttpUtils.httpPost(url, JSONObject.fromObject(params));
        String ticket=jsonObject.getString(Consts.ticket);
        return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket;
    }


    public String getAccess_token() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Consts.appid + "&secret=" + Consts.secret;
        return HttpUtils.httpGet(url).getString(Consts.access_token);
    }

    /**
     * 直播授权
     *
     * @return
     */
    public String getZbAuth() {
        return null;
    }
}